package top.tenebrous.yzl.im.context;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.tenebrous.yzl.im.interceptor.ImWebsocketInterceptor;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yazhang6
 * @Classname ImContext
 * @Description TODO
 * @Date 2023/11/12 1:38 PM
 * @Created by zhangya
 */
@Component
public class ImContext {

    private static final Map<String ,ImWebsocketInterceptor> INTERCEPTOR_MAP = new ConcurrentHashMap<>();

    /**
     * 获取拦截集合
     *
     * @return
     */
    public List<ImWebsocketInterceptor> getInterceptorList() {
        List<ImWebsocketInterceptor> list = new ArrayList<>();
        INTERCEPTOR_MAP.forEach((k, v) -> list.add(v));
        return list;
    }

    /**
     * 设置拦截器
     *
     * @param key
     * @param interceptor
     */
    public void setInterceptorMap(String key, ImWebsocketInterceptor interceptor) {
        INTERCEPTOR_MAP.put(key, interceptor);
    }

    /**
     * 对拦截器进行排序
     *
     * @return
     */
    public List<Map.Entry<ImWebsocketInterceptor, Integer>> handlerInterceptorSorted() {
        Map<ImWebsocketInterceptor, Integer> map = new HashMap<>();
        // 处理扩展拦截顺序
        List<ImWebsocketInterceptor> interceptors = this.getInterceptorList();
        for (ImWebsocketInterceptor interceptor : interceptors) {
            int sorted = Integer.MAX_VALUE - 10000;
            // 判断当前实现类是否有 Order注解
            Order order = interceptor.getClass().getAnnotation(Order.class);
            if (Objects.isNull(order)) {
                // 如果没有order注解，则判断该实现类，是否实现了Ordered接口
                if (interceptor instanceof Ordered) {
                    sorted = ((Ordered) interceptor).getOrder();
                }
            } else {
                sorted = order.value();
            }
            map.put(interceptor, sorted);
        }
        List<Map.Entry<ImWebsocketInterceptor,Integer>> sortList = new ArrayList<>(map.entrySet());
        Collections.sort(sortList, new Comparator<Map.Entry<ImWebsocketInterceptor,Integer>>() {
            @Override
            public int compare(Map.Entry<ImWebsocketInterceptor,Integer> o1, Map.Entry<ImWebsocketInterceptor,Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        return sortList;
    }

}
